from datetime import datetime

import jwt
from flask import jsonify, current_app, request
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity, decode_token
from . import user
from .ai_client import generate_response
from .. import db
from ..models import Dialog, User, KnowledgeBase
from werkzeug.security import check_password_hash, generate_password_hash
from datetime import timedelta


@user.route('/message', methods=['POST'])
def handle_message():
    # 获取信息
    # 从请求中获取 token
    token = request.get_json().get('token')
    if not token:
        return jsonify({"msg": "缺少 token"}), 400
    decoded_token = jwt.decode(token, 'ailab', algorithms=["HS256"])
    user_id = decoded_token.get('identity')
    data = request.get_json()
    # 校验输入
    if not data or 'message' not in data:
        return jsonify({"error": "Invalid input"}), 400

    # 处理用户消息
    user_input = data['message']
    # print(user_id, user_input)
    # 情感分析
    # emotion_result = ai.analyze_emotion(user_input)
    emotion_result = {"label": "焦虑", "score": 0.2}
    # # 生成对话历史摘要
    history = Dialog.query.filter_by(user_id=user_id) \
        .order_by(Dialog.created_at.desc()) \
        .limit("200") \
        .all()
    history_summary = "\n".join([f"{d.role}: {d.content}" for d in reversed(history)])
    #
    # # # 构建prompt
    # prompt = f"""
    # [用户情绪分析] {emotion_result['label']} (置信度: {emotion_result['score']:.2f})
    # [历史对话摘要]
    # {history_summary}
    #
    # 用户新消息：{user_input}
    # 请以专业心理咨询师的身份给出回复：
    # """
    prompt = f"""
        {user_input}
        请以专业心理咨询师的身份用一段话的中文给出回复
        """
    # 获取AI回复
    ai_response = generate_response(prompt)
    # ai_response = '作为正在备战考研的你，此刻的焦虑就像书桌上堆积的参考书一样真实而具体。我想先给你一个隔空的拥抱——这段咬着牙向前奔跑的日子，注定会成为你生命里闪着微光的勋章。压力不是你的敌人，它是大脑在提醒你需要调整呼吸节奏了。试着把"我必须考上"的执念，换成"我正在创造人生新可能性"的期待，那些让你辗转反侧的复习漏洞，其实都可以拆解成每天攻克2-3个知识点的具体动作。记住午休时看看窗外摇曳的树影，晚饭后绕着操场走满5圈，让身体和心灵保持同频的节奏。当你背专业课时突然心慌，不妨摸摸口袋里的幸运硬币，感受它被体温焐热的踏实感；做数学题卡壳时，就想象这是未来导师悄悄送来的思维锻炼礼包。这场考试检验的不仅是知识储备，更是你与不确定性和平共处的能力。请相信，那个每天清晨准时坐在图书馆的你，那个熄灯后还打着小台灯整理错题的你，正在用每个当下的坚持书写着属于自己的英雄之旅。无论最终结果如何，这段全心投入的时光，早已让你成为了更坚韧、更清醒的自己。'
    # 保存对话记录
    user_dialog = Dialog(
        user_id=user_id,
        role='user',
        content=user_input,
        emotion_score=emotion_result['score']
    )
    ai_dialog = Dialog(
        user_id=user_id,
        role='ai',
        content=ai_response
    )
    db.session.add_all([user_dialog, ai_dialog])
    db.session.commit()

    return jsonify({
        "response": ai_response,
        "emotion": emotion_result
    })


@user.route('/login', methods=['POST'])
def login():
    # 获取请求的数据
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    # 验证用户
    user = User.query.filter_by(username=username).first()
    if user is None or not check_password_hash(user.password_hash, password):
        return jsonify({"msg": "账号或密码错误"}), 401

    # 生成 JWT token，有效期为 24 小时
    access_token = jwt.encode({
        'identity': user.id,
        'exp': datetime.utcnow() + timedelta(hours=24)
    }, 'ailab', algorithm='HS256')

    # 更新用户的最后登录时间
    user.last_login = datetime.utcnow()
    db.session.commit()

    return jsonify(access_token=access_token), 200


@user.route('/register', methods=['POST'])
def register():
    # 获取请求的数据
    data = request.get_json()

    # 验证输入数据
    student_id = data.get('student_id')
    username = data.get('username')
    password = data.get('password')
    emergency_contact = data.get('emergency_contact')

    # 检查必填字段
    if not student_id or not username or not password:
        return jsonify({"msg": "请完善信息"}), 400

    # 检查学生ID是否已存在
    if User.query.filter_by(student_id=student_id).first() is not None:
        return jsonify({"msg": "学号已存在"}), 400

    # 创建新用户并设置属性
    new_user = User(
        student_id=student_id,
        username=username,
        password_hash=generate_password_hash(password),  # 安全地哈希密码
        emergency_contact=emergency_contact
    )

    # 将用户添加到数据库
    db.session.add(new_user)
    db.session.commit()

    return jsonify({"msg": "User registered successfully"}), 201


@user.route("/get_person_message", methods=["POST"])
def get_person_message():
    try:
        # 从请求中获取 token
        token = request.get_json().get('token')
        if not token:
            return jsonify({"msg": "缺少 token"}), 400
        decoded_token = jwt.decode(token, 'ailab', algorithms=["HS256"])
        user_id = decoded_token.get('identity')  # 根据你的token结构获取user_id

        # 获取用户信息
        user_info = User.query.get(user_id)

        if user_info:
            response = {
                "username": user_info.username,
                "student_id": user_info.student_id,
                "emergency_contact": user_info.emergency_contact
            }
            return jsonify(response), 200
        else:
            return jsonify({"msg": "用户信息未找到"}), 404

    except jwt.ExpiredSignatureError:
        return jsonify({"msg": "token 已过期"}), 401
    except jwt.InvalidTokenError:
        return jsonify({"msg": "无效的 token"}), 401
    except Exception as e:
        return jsonify({"msg": "服务器错误", "error": str(e)}), 500


@user.route("/update_emergency_contact", methods=["POST"])
def update_emergency_contact():
    try:
        # 从请求中获取 token
        token = request.get_json().get('token')
        if not token:
            return jsonify({"msg": "缺少 token"}), 400
        decoded_token = jwt.decode(token, 'ailab', algorithms=["HS256"])
        user_id = decoded_token.get('identity')
        emergency_contact = request.get_json().get('emergency_contact')
        # 获取用户信息
        user_info = User.query.get(user_id)

        if user_info:
            user_info.emergency_contact = emergency_contact
            db.session.commit()
            return jsonify({"msg": "紧急联系人更新成功"}), 200  # 成功时返回
        else:
            return jsonify({"msg": "用户信息未找到"}), 404

    except jwt.ExpiredSignatureError:
        return jsonify({"msg": "token 已过期"}), 401
    except jwt.InvalidTokenError:
        return jsonify({"msg": "无效的 token"}), 401
    except Exception as e:
        return jsonify({"msg": "服务器错误", "error": str(e)}), 500


@user.route("/update_password", methods=["POST"])
def update_password():
    try:
        # 从请求中获取 token
        token = request.get_json().get('token')
        if not token:
            return jsonify({"msg": "缺少 token"}), 400
        decoded_token = jwt.decode(token, 'ailab', algorithms=["HS256"])
        user_id = decoded_token.get('identity')
        new_password = request.get_json().get('new_password')
        # 获取用户信息
        user_info = User.query.get(user_id)

        if user_info:
            user_info.password = new_password
            db.session.commit()
            return jsonify({"msg": "密码修改成功"}), 200  # 成功时返回
        else:
            return jsonify({"msg": "用户信息未找到"}), 404

    except jwt.ExpiredSignatureError:
        return jsonify({"msg": "token 已过期"}), 401
    except jwt.InvalidTokenError:
        return jsonify({"msg": "无效的 token"}), 401
    except Exception as e:
        return jsonify({"msg": "服务器错误", "error": str(e)}), 500


@user.route("/get_knowledge", methods=["GET"])
def get_knowledge():
    try:
        # 获取知识库
        knowledge = KnowledgeBase.query.all()

        if knowledge:
            response = [{
                "id": item.id,
                "title": item.title,
                "category": item.category,
                "author": item.author,
                "updated_at": item.updated_at.isoformat(),  # 转换为 ISO 格式字符串
                "content": item.content
            } for item in knowledge]
            return jsonify(response), 200
        else:
            return jsonify({"msg": "知识库信息未找到"}), 404

    except Exception as e:
        return jsonify({"msg": "服务器错误", "error": str(e)}), 500
